import pathlib
import time
import re
import typing
import os
import json
import yaml
import ctypes
import psutil
import subprocess
import requests
import winsound
import datetime
import rich
import playsound
from selenium.webdriver.edge.webdriver import WebDriver
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions
from selenium.common.exceptions import *



if __name__ == '__main__':
    # 切换工作目录到当前脚本所在目录
    os.chdir(pathlib.Path(__file__).parent.absolute().resolve().__str__())
    Modify_Time = "2025年7月28日17:25:52"
    print(f"当前【淘宝】自动化脚本的版本日期是 : 【{Modify_Time}】")

    # 判断是否是否启动浏览器
    from Wrapper.Taobao.Initialization import *
    CheckResul_Process = Checkout_Has_Msedge_Process()  # 检测是否有 msedge.exe 进程
    if(CheckResul_Process == False):
        Start_Debugmode_Browser()
    else:
        CheckResul_DebugModu = Checkout_Debug_Mode_Activate()   # 检测是否处于调试模式
        if(CheckResul_DebugModu == False):
            _select_execute = Custom_Message(text="当前不是调试环境\n请问是否需要关闭所有 msedge.exe 进程\n重新打开!",type=1)
            # 1.判断选择那种方式启动浏览器
            match _select_execute:
                case 1:
                    Close_All_Msedge_Process()
                    Start_Debugmode_Browser()
                case 2:
                    exit(0)
                case _:
                    exit(0)


    # 基础配置
    driver = Fast_Create_WebDriver_Wait_Action()
    Goto_CurrentActivateUrl(driver)
    # ConfigData = yaml.safe_load(stream=open(file="./config.yaml",mode="r",encoding="utf-8"))['TaoBao']
    ConfigData = json.load(fp=open(file="./config.json",mode="r",encoding="utf-8"))['TaoBao']



    # 选择类目
    # from Wrapper.Taobao.Select_Category import *
    from Wrapper.Taobao.OpenUrl import *
    from Wrapper.Taobao.Select_Category import *
    Goto_Select_Category(driver)
    
    On_SelectPage_Switch_ByFind(driver)
    On_SelectPage_Select_FirstCategory(driver,ConfigData['FirstCategory'])
    On_SelectPage_Select_SecondCategory(driver,ConfigData['SecondCategory'])
    On_SelectPage_Select_CatePro(driver,"无品牌/无注册商标")
    Goto_Parameter_Input(driver)
    


    # 填写基础参数
    from Wrapper.Taobao.Input_Parameters import *
    for AttributeName,AttributeValue in ConfigData['TBBasicParameters'].items():
        On_InputPage_InputBasicParameters(driver=driver,
                                          AttributeName=AttributeName,
                                          AttributeValue=AttributeValue)


    

    # 上传详情图
    from Wrapper.Taobao.Directory import *
    from Wrapper.Taobao.UploadDetailImage import *
    DetailImageDirectory = GetExistsDirectory(ConfigData['DetailDirectoryFilterList'])
    if DetailImageDirectory:
        On_InputPage_UploadDetail_Picture_ByDirectory(driver=driver,picture_directory_path=DetailImageDirectory)





    # 上传视频
    # MainVideoDirectory = GetExistsDirectory(ConfigData['MainVideoDirectoryFilterList'])
    # if MainVideoDirectory:
    #     On_InputPage_UploadMain_Video_ByDirectory(driver,wait,actions,MainVideoDirectory)





    # 填写 Sku
    from Wrapper.Taobao.Input_Sku import *
    SkuImageDirectory = GetExistsDirectory(ConfigData['SkuImageDirectoryFilterList'])
    for root,dirs,files in os.walk(SkuImageDirectory):
        for file in files:
            if file.endswith(".jpeg") or file.endswith(".jpg") or file.endswith(".png"):
                skuimagepath = pathlib.Path(os.path.join(root, file)).absolute().resolve()
                basename = pathlib.Path(os.path.join(root, file)).absolute().resolve().stem
                # colorname = re.sub(r'[^\u4e00-\u9fff]', '', basename)
                On_InputPage_UploadSkuPicture_And_SetSkuName(driver=driver,
                                                             SkuName=basename,
                                                             Picture_Name=skuimagepath)




    
    # 填写尺码
    from Wrapper.Taobao.Input_SizeType import *
    On_InputPage_SelectSizeChat(driver=driver,
                   SizeCharType=ConfigData['ChartSizeType'],
                   SizeCharList=ConfigData['ChartSizeList'])


    


    # 填写价格和编码
    from Wrapper.Taobao.Input_Price_Code import *
    On_InputPage_Input_Batch_Price_And_Code(driver=driver,
                               Number=ConfigData['Number'],
                               Price=ConfigData['Price'],
                               Product_Code=ConfigData['Code'])





    # 上传 1:1 主图
    from Wrapper.Taobao.UploadMainImage import *
    MainmageDirectory = GetExistsDirectory(ConfigData['MainDirectoryFilterList'])
    if MainmageDirectory:
        On_InputPage_UploadMain_1b1_Picture_ByDirectory(driver=driver,picture_directory_path=MainmageDirectory,Delay=5)





    # 上传 3:4 主图
    MainmageDirectory = GetExistsDirectory(ConfigData['MainDirectoryFilterList'])
    if MainmageDirectory:
        On_InputPage_UploadMain_3b4_Picture_ByDirectory(driver=driver,picture_directory_path=MainmageDirectory,Delay=5)





    # 填写其他参数
    from Wrapper.Taobao.Input_Other_Params import *
    On_InputPage_InputOhtherParameters(driver=driver)
    On_InputPage_InputLogistics(driver=driver,Logistics_Template_Name=ConfigData['Logistics_Template_Name'])




    
    # 填写商品尺寸表
    from Wrapper.Taobao.Input_SizeChat import *
    On_InputPage_SizeChatTable(driver=driver,TemplateName=ConfigData['TB_SIzeCharTable'])




    # 滚动到标题
    On_HtmlPage_Scroll_To_Top(driver=driver)




    # 搜索同款
    from Wrapper.Taobao.Find_Same import *
    Find_MainImageTitle(driver=driver,Picture_Path=pathlib.Path(MainmageDirectory).iterdir().__next__().absolute().resolve())
    
    
    
    
    # 播放声音
    playsound.playsound(sound=pathlib.Path("./Resource/TaobaoSound.mp3").absolute())




    # 结束程序
    driver.quit()
    input(f"程序结束 : 请按任意键退出...")  # 等待用户输入以结束程序